package com.reesechou.controller.admin;

import com.reesechou.javabean.Category;
import com.reesechou.service.CategoryService;
import org.directwebremoting.util.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by 小星打屁屁 on 2015/4/11.
 * contact me ==>243709758@qq.com
 */
@Controller
@RequestMapping("/jsp/admin/content")
public class CategoryController {
   private static Logger logger =  Logger.getLogger(CategoryController.class);

    private  static  String  LIST_PAGE = "category_list";
    private  static  String  ADD_PAGE = "category_add";

    @Autowired
    private CategoryService categoryService ;

    @RequestMapping("/category_list")
    public String getCategoryList(HttpServletRequest request ,HttpServletResponse response ,Model model){
        logger.info("跳转到文章分类的列表");
        List<Category> list = categoryService.findAllCategory();
        model.addAttribute("categoryList",list);
        return  LIST_PAGE ;
    }
    @RequestMapping(value = "/category_add",method = RequestMethod.GET)
    public String toAddPage(HttpServletRequest request ,HttpServletResponse response ,Model model){
        logger.info("跳转到新增页面");
        List<Category> list = categoryService.findAllCategory();
        model.addAttribute("categorys",list);
        return ADD_PAGE ;
    }
    @RequestMapping(value = "/category_add",method = RequestMethod.POST)
    public String doAddPage(HttpServletRequest request ,HttpServletResponse response ,Category category,Model model){
        System.out.println("==========="+category.getName());
        createDataPrepare(category);
        if (categoryService.save(category)==1){
            logger.info("保存成功");
        }else{
            logger.error("保存失败");
        }

        return "redirect:"+ADD_PAGE ;
    }

    /**
     * 创建文章分类的一些相关数据的设置和初始化
     * @param category
     */
    public void createDataPrepare(Category category){
        Date createTime = new Date();
        int priority = 0;
        int trash = 0;
        String type = null;

        category.setCreateTime(createTime);
        category.setPriority(priority);
        category.setTrash(trash);
        category.setType(type);

    }
}
